/*
 * MIT License
 *
 * Copyright (c) 2018 yadu.liu
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
package cn.jingyuan.swan.gw.fallback;

import cn.jingyuan.bee.exception.ErrorCode;
import cn.jingyuan.bee.fastjson.FastJsonUtils;
import cn.jingyuan.swan.cloud.core.ExCode;
import cn.jingyuan.swan.cloud.core.Result;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;


/**
 * 服务响应超时熔断
 */
@Slf4j
@Component
public class FailureFallbackProvider implements FallbackProvider {

    // https://www.cnblogs.com/okong/p/springcloud-ten.html

    @Override
    public String getRoute() {
        // 表明是为哪个微服务提供回退，"*" 表示全部
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable throwable) {
        if (log.isDebugEnabled()) {
            log.debug(this.getClass().getSimpleName() + " execute, route={}", route, throwable);
        }

        ExCode exCode = ExCode.SERVICE_UNAVAILABLE;
        HttpStatus httpStatus = HttpStatus.SERVICE_UNAVAILABLE;

        // FIXME HystrixBadRequestException HystrixRuntimeException HystrixTimeoutException
        if (throwable instanceof HystrixTimeoutException) {
            exCode = ExCode.GATEWAY_TIMEOUT;
            httpStatus = HttpStatus.GATEWAY_TIMEOUT;
        }

        return this.response(httpStatus, exCode);
    }

    private ClientHttpResponse response(final HttpStatus httpStatus, final ErrorCode errCode) {
        return new ClientHttpResponse() {

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return httpStatus;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return httpStatus.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return httpStatus.getReasonPhrase();
            }

            @Override
            public void close() {
                // default implementation ignored
            }

            @Override
            public InputStream getBody() throws IOException {
                Result<?> result = new Result()
                    .setCode(errCode.getCode())
                    .setCodeMsg(errCode.getCodeMsg())
                    .setHttpStatus(httpStatus.value());

                String body = FastJsonUtils.json(result);

                return new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                return headers;
            }
        };
    }

}
